#include "syncfiles.h"
#include "ui_syncfiles.h"
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QDateTime>
#include <QRegExp>

SyncFiles::SyncFiles(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SyncFiles)
{
    ui->setupUi(this);

    Init();
}

SyncFiles::~SyncFiles()
{
    delete SyncTimer;
    delete ui;
}

void SyncFiles::Init()
{
    InitCtrls();
    IsStart = false;
    SyncTimer = new QTimer;
    connect(SyncTimer, SIGNAL(timeout()), this, SLOT(SyncFileTimerout()));
}

void SyncFiles::InitCtrls()
{
    this->setLayout(ui->vLayoutMain);
    QSettings cf("config.cfg", QSettings::IniFormat);
    SrcPath = cf.value("/Path/Src").toString();
    ui->lEditSrc->setText(SrcPath);
    DestPath = cf.value("/Path/Dest").toString();
    ui->lEditDest->setText(DestPath);
    ui->lEditInterval->setText("5");
    StartTime = cf.value("/Project/StartTime").toString();
    if(StartTime.isEmpty()) {
        StartTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        cf.setValue("/Project/StartTime", StartTime);
    }
    ui->lEditStartTime->setText(StartTime);
}

QString SyncFiles::GetFolderPath()
{
    return QFileDialog::getExistingDirectory(this, "Choose a Directory");
}

int SyncFiles::RecusionFindFiles(QString Folder, QVector<QString> &List)
{
    QDir dir(Folder);
    int Cnt = 0;
    if(!dir.exists())
        return Cnt;
    QFileInfoList infoList = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    for(auto i = 0; i < infoList.size(); i++) {
        QString name = infoList.at(i).absoluteFilePath();
        List.append(name);
        if(infoList.at(i).isDir())
            RecusionFindFiles(name, List);
    }
    return Cnt;
}

bool SyncFiles::RegexFindTime(QString data)
{
    QRegExp re1("\\d{4}-\\d{2}");
    QRegExp re2("\\d{4}-\\d{2}-\\d{2}");
    QRegExp re3("\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}");
    QRegExp re4("_\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}.");
    if(re4.indexIn(data) != -1) {
        QString STime = ui->lEditStartTime->text();
        QString Temp = re4.cap(0);
        Temp = Temp.left(Temp.indexOf("."));
        Temp = Temp.right(Temp.length() - Temp.indexOf("_") - 1);
        QString Date = Temp.left(Temp.indexOf("_"));
        QString Time = Temp.right(Temp.length() - Temp.indexOf("_") - 1);
        Time.replace("-", ":");
        Date = Date + " " + Time;
        if(Date >= STime) {
            StartTime = Date;
            return true;
        }
        else
            return false;
    }
    if(re3.indexIn(data) != -1) {
        QString STime = ui->lEditStartTime->text();
        QString Temp = re3.cap(0);
        QString Date = Temp.left(Temp.indexOf("_"));
        QString Time = Temp.right(Temp.length() - Temp.indexOf("_") - 1);
        Time.replace("-", ":");
        Date = Date + " " + Time;
        if(Date >= STime)
            return true;
        else
            return false;
    }
    if(re2.indexIn(data) != -1) {
        QString time = re2.cap(0);
        QString STime = ui->lEditStartTime->text();
        STime = STime.left(STime.indexOf(" "));
        if(time >= STime)
            return true;
        else
            return false;
    }
    if(re1.indexIn(data) != -1) {
        QString time = re1.cap(0);
        QString STime = ui->lEditStartTime->text();
        STime = STime.left(STime.indexOf(" "));
        STime = STime.left(STime.lastIndexOf("-"));
        if(time >= STime)
            return true;
        else
            return false;
    }
    return true;
}

void SyncFiles::SyncFile()
{
    QVector<QString> SrcList, DestList;
    RecusionFindFiles(SrcPath, SrcList);
    RecusionFindFiles(DestPath, DestList);
    for(auto i = 0; i < SrcList.size(); i++) {
        bool IsFind = false;
        QString SrcName = SrcList.at(i);
        SrcName.replace(SrcPath + "/", "");
        for(auto j = 0; j < DestList.size(); j++) {
            QString DestName = DestList.at(j);
            DestName.replace(DestPath + "/", "");
            if(SrcName == DestName) {
                IsFind = true;
                break;
            }
        }
        if(!IsFind) {
            QString Path = DestPath + "/" + SrcName;
            QFileInfo info(SrcList.at(i));
            if(info.isDir()) {
                QDir dir(Path);
                dir.mkpath(Path);
            }
            else {
                QString Temp = Path.left(Path.lastIndexOf("/"));
                QDir dir(Temp);
                dir.mkpath(Temp);
                QFile::copy(SrcList.at(i), Path);
            }
        }
    }
    ui->lEditStartTime->setText(StartTime);
    if(SyncTimer->isActive())
        SyncTimer->stop();
     SyncTimer->start(ui->lEditInterval->text().toInt() * 1000);
}

void SyncFiles::on_BtnSrc_clicked()
{
    SrcPath = GetFolderPath();
    ui->lEditSrc->setText(SrcPath);
    QSettings cf("config.cfg", QSettings::IniFormat);
    cf.setValue("/Path/Src", SrcPath);
}

void SyncFiles::on_BtnDest_clicked()
{
    DestPath = GetFolderPath();
    ui->lEditDest->setText(DestPath);
    QSettings cf("config.cfg", QSettings::IniFormat);
    cf.setValue("/Path/Dest", DestPath);
}

void SyncFiles::on_BtnStart_clicked()
{
    if(!IsStart) {
        if(SrcPath.isEmpty() || DestPath.isEmpty()) {
            QMessageBox::information(this, "提示信息", "目录不能为空！", QMessageBox::Ok, QMessageBox::Ok);
            return;
        }
        if(SrcPath == DestPath) {
            QMessageBox::information(this, "提示信息", "请选择两个不同的目录！", QMessageBox::Ok, QMessageBox::Ok);
            return;
        }
        if(ui->lEditInterval->text().isEmpty()) {
            QMessageBox::information(this, "提示信息", "时间间隔不能为空！", QMessageBox::Ok, QMessageBox::Ok);
            return;
        }
        IsStart = true;
        ui->BtnStart->setText(QStringLiteral("停止"));
        ui->lEditSrc->setEnabled(false);
        ui->BtnSrc->setEnabled(false);
        ui->lEditDest->setEnabled(false);
        ui->BtnDest->setEnabled(false);
        ui->lEditStartTime->setEnabled(false);
        ui->lEditInterval->setEnabled(false);
        SyncFile();
    }
    else {
        IsStart = false;
        ui->BtnStart->setText(QStringLiteral("开始"));
        ui->lEditSrc->setEnabled(true);
        ui->BtnSrc->setEnabled(true);
        ui->lEditDest->setEnabled(true);
        ui->BtnDest->setEnabled(true);
        ui->lEditStartTime->setEnabled(true);
        ui->lEditInterval->setEnabled(true);
        if(SyncTimer->isActive())
            SyncTimer->stop();
    }
}

void SyncFiles::SyncFileTimerout()
{
    if(SyncTimer->isActive())
        SyncTimer->stop();
    SyncFile();
}

void SyncFiles::on_lEditStartTime_editingFinished()
{
    StartTime = ui->lEditStartTime->text();
    QSettings cf("config.cfg", QSettings::IniFormat);
    cf.setValue("/Project/StartTime", StartTime);
}
